﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Mr.HttpBodyWrapper
{
    public class KeyValuesHttpBodyWrapper : HttpBodyWrapperBase
    {
        public KeyValuesHttpBodyWrapper(params IQueryParameter[] queryParameters)
            : base(queryParameters)
        { }

        public override string ContentType
        {
            get
            {
                return "application/x-www-form-urlencoded";
            }
        }

        private string GetBodyString()
        {
            StringBuilder sbuiler = new StringBuilder();
            if (this.ParamsCount > 0)
            {
                foreach (IParameter ip in this.Parameters)
                {
                    QueryParameter qp = ip as QueryParameter;
                    if (qp != null)
                    {
                        sbuiler.AppendFormat("{0}={1}&", qp.Name, qp.Value);
                    }
                }
                if (sbuiler.Length > 0)
                {
                    sbuiler.Remove(sbuiler.Length - 1, 1);
                }
            }
            return sbuiler.ToString();
        }

        public override byte[] ToBodyData()
        {
            return Encoding.UTF8.GetBytes(this.GetBodyString());
        }
    }
}
